import base64
import json
import pickle

import jwt
from django.http import JsonResponse
from django.shortcuts import render
from django.http import JsonResponse, HttpResponseBadRequest
from django.shortcuts import render

# Create your views here.
from django.views import View
from django_redis import get_redis_connection
from rest_framework.permissions import IsAuthenticated
from rest_framework.views import APIView

from apps.goods.models import SKU
# Create your views here.
from tea import settings


class CartsView(APIView):
    """购物车管理"""
    permission_classes = [IsAuthenticated ]
    def post(self, request):
        """添加购物车"""
        # 接收和校验参数
        json_date = json.loads(request.body)
        sku_id = json_date.get("sku_id")  # 商品id
        count = json_date.get("count")  # 数量
        # 判断用户是否登录

        try:
            sku = SKU.objects.get(id=sku_id)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "商品不存在"})
        try:
            count = int(count)
        except Exception as e:
            print(e)
            return JsonResponse({"code": 400, "errmsg": "数量错误"})

        user = request.user

        if user.is_authenticated:
            # 用户已登录，操作redis购物车
            redis_conn = get_redis_connection('carts')
            pl = redis_conn.pipeline()
            # 新增购物车数据
            pl.hincrby('cart_%s' % user.id, sku_id, count)
            # 新增选中的状态
            pl.sadd('selected_%s' % user.id, sku_id)
            # 执行管道
            pl.execute()
            # 响应结果
            return JsonResponse({'code': 0, 'errmsg': '添加购物车成功'})
        else:
            return JsonResponse({'code': 400, 'errmsg': '请登录'})


    def get(self, request):
        """展示购物车"""
        user = request.user
        if user.is_authenticated:
            # 用户已登录，查询redis购物车
            redis_conn = get_redis_connection('carts')
            # 获取redis中的购物车数据
            redis_cart = redis_conn.hgetall('cart_%s' % user.id)
            # 获取redis中的选中状态
            selected_skuids = redis_conn.smembers('selected_%s' % user.id)

            # 将redis中的数据构造成跟cookie中的格式一致，方便统一查询
            carts = {}
            for sku_id, count in redis_cart.items():
                carts[int(sku_id)] = {
                    'count': int(count),
                    'selected': sku_id in selected_skuids
                }
        else:
            # 用户未登录，查询cookies购物车
            cart_cookie = request.COOKIES.get("cart")
            if cart_cookie:
                # 将cart_str转成bytes,再将bytes转成base64的bytes,最后将bytes转字典
                carts = pickle.loads(base64.b64decode(cart_cookie))
            else:
                carts = {}

        sku_ids = carts.keys()
        skus = SKU.objects.filter(id__in=sku_ids)

        sku_list = []
        for sku in skus:
            sku_list.append({
                "id": sku.id,
                "name": sku.name,
                "price": sku.price,
                'cost_price':sku.cost_price,
                "count": carts[sku.id]["count"],
                "selected": carts[sku.id]["selected"],
            })
        return JsonResponse({'code': 0, 'errmsg': 'OK', 'cart_skus': sku_list})

    def put(self, request):
        user = request.user

        json_data = json.loads(request.body)

        sku_id = json_data.get('sku_id')
        count = json_data.get('count')
        selected = json_data.get('selected')

        try:
            sku = SKU.objects.get(id=sku_id)

        except Exception as e:
            print(e)
            return HttpResponseBadRequest('商品sku_id不存在')

        try:
            count = int(count)

        except Exception as e:
            print(e)
            return HttpResponseBadRequest('参数count有误')

        if user.is_authenticated:
            redis_coon = get_redis_connection('carts')

            redis_coon.hset("cart_%s" % user.id, sku_id, count)

            if selected:
                redis_coon.sadd("selected_%s" % user.id, sku_id)
            else:
                redis_coon.srem("selected_%s" % user.id, sku_id)

            cart_sku = {"count": count, "selected": selected, "sku_id": sku_id}

            return JsonResponse({'code': 0, "errmsg": "ok", "cart_sku": cart_sku})

        else:
            return JsonResponse({'code': 400, "errmsg": "错误", })

    def delete(self, request):
        user = request.user

        json_data = json.loads(request.body)

        sku_id = json_data.get('sku_id')

        try:
            sku = SKU.objects.get(id=sku_id)

        except Exception as e:
            print(e)
            return HttpResponseBadRequest("商品sku_id不存在")

        if user.is_authenticated:
            redis_conn = get_redis_connection("carts")

            redis_conn.hdel("cart_%s" % user.id, sku_id)

            redis_conn.srem("selected_%s", user.id, sku_id)

            return JsonResponse({"code": 0, "errmsg": "ok"})

        else:

            return JsonResponse({"code": 400, "errmsg": "删除错误"})